const { Service } = require("egg");
const { Op } = require("sequelize");

class TopicLessonPersonService extends Service {
    async list(lessonId) {
        return await this.app.model.TopicLessonPerson.findAll({
            where: {
                lessonId
            },
            order: [['updatedAt', 'DESC']],
            raw: true,
        });
    }
    async create(lessonId, userIds) {
        const { ctx } = this;
        const existingRecords = await ctx.model.TopicLessonPerson.findAll({
            where: {
                lessonId,
                userId: { [Op.or]: userIds },
            },
        });

        const existingUserIds = existingRecords.map(record => record.userId);
        const newUserIds = userIds.filter(userId => !existingUserIds.includes(userId));

        const data = newUserIds.map(userId => ({
            lessonId,
            userId,
        }));

        if (newUserIds.length > 0) {
            return await ctx.model.TopicLessonPerson.bulkCreate(data);
        } else {
            return existingRecords;
        }
    }

    async delete({ userId, lessonId }) {
        return await this.app.model.TopicLessonPerson.destroy({
            where: { userId, lessonId },
        });
    }

    async update(id, updateData) {

        const TopicInfo = await this.app.model.TopicLessonPerson.findOne({
            where: { id },
        });
        if (TopicInfo) {

            const updatedTopic = await this.app.model.TopicLessonPerson.update(
                updateData,
                {
                    where: { id },
                });
            return updatedTopic[0] ? updatedTopic[0] : null;
        }
        return null;
    }


    async updateCertificate(certificateId, updateData) {


        const TopicInfo = await this.app.model.TopicLessonPerson.findOne({
            where: { ...updateData },
        });
        console.log("TopicInfo", TopicInfo)

        if (TopicInfo) {

            const updatedTopic = await this.app.model.TopicLessonPerson.update(
                {
                    certificateId
                },
                {
                    where: { ...updateData },
                });
            return updatedTopic[0] ? updatedTopic[0] : null;
        }
        return null;
    }


    async verify({ lessonId, userId }) {
        try {
            const record = await this.ctx.model.TopicLessonPerson.findOne({
                where: {
                    lessonId,
                    userId,
                },
            });
            return record !== null;
        } catch (error) {
            return false;
        }
    }

    async getItem({ lessonId, userId }) {
        return await this.app.model.TopicLessonPerson.findOne({
            where: { userId, lessonId },
            raw: true,
        });
    }
}

module.exports = TopicLessonPersonService;
